package com.cxs.handler.impl;

import com.cxs.dao.impl.BaseDaoImpl;
import com.cxs.handler.ResultHandler;
import com.cxs.utils.UnderlineToHumpCaseUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Project: jdbc
 * @Author: cxs2014501@163.com
 * @Create: 2022/8/31 15:34
 * @Description:
 **/
public class ResultBeanAsListHandler<T> implements ResultHandler<List<T>> {

    private static Logger logger = LogManager.getLogger(BaseDaoImpl.class);

    private Class<T> tClass;

    public ResultBeanAsListHandler(Class tClass){
        this.tClass = tClass;
    }
    @Override
    public List<T> resultHandle(ResultSet resultSet) {
        List<T> result = new ArrayList<>();
        List<String> fildsNames = (tClass.getDeclaredFields() != null && tClass.getDeclaredFields().length > 0) ?
                Arrays.stream(tClass.getDeclaredFields()).map(Field::getName).collect(Collectors.toList()) :
                new ArrayList<>(0);
        try {
            ResultSetMetaData metaData = resultSet.getMetaData();
            while (resultSet.next()) {
                T obj = this.tClass.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    try {
                        String name = metaData.getColumnLabel(i);
                        if (!fildsNames.contains(UnderlineToHumpCaseUtil.underlineToHumpCase(name))) {

                        } else {
                            PropertyDescriptor pd = new PropertyDescriptor(UnderlineToHumpCaseUtil.underlineToHumpCase(name), tClass);
                            pd.getWriteMethod().invoke(obj, resultSet.getObject(name));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        continue;
                    }
                }
                result.add(obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
